<template>
  <div class="app-container">

    <!-- 搜索 -->
    <!-- model：表单数据对象 -->
    <!-- inline：true，行内表单模式	 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <!-- prop：表单域 model 字段，在使用 validate、resetFields 等方法的情况下，该属性是必填的	 -->
      <el-form-item label="频道名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入频道名称" @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <el-form-item label="频道分类" prop="ctype">
        <!-- 为el-select设置clearable属性，则可将选择器清空。需要注意的是，clearable属性仅适用于单选。 -->
        <el-select v-model="queryParams.ctype" placeholder="请选择频道分类" clearable>
          <!-- label:选项的标签，若不设置则默认与 value 相同	disabled:是否禁用该选项【可以通过后台返回是否禁用】	 -->
          <el-option v-for="dict in dict.type.gxh_channel_type" :key="dict.value" :label="dict.label" :value="dict.value" :disabled="dict.value == 30">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期" prop="querydate">
        <el-date-picker v-model="queryParams.querydate" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholde="开始日期" end-placeholde="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮信息 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- plain:是否朴素按钮	 -->
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="!canDelete" @click="handleDeleteBatch">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportEasyExcel">导出【easyExcel】</el-button>
      </el-col>
      <!-- 右侧显示按钮【显隐、刷新】 -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格信息 -->
    <!-- stripe属性可以创建带斑马纹的表格 -->
    <!-- selection-change:当选择项发生变化时会触发该事件	 -->
    <el-table v-loading="loading" :data="channelList" @selection-change="handleSelectionChange" stripe>

      <!-- 实现多选非常简单: 手动添加一个el-table-column，设type属性为selection即可； -->
      <el-table-column type="selection" align="center"></el-table-column>

      <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
      <el-table-column label="频道名称" prop="name" width="240" align="center"></el-table-column>

      <el-table-column label="频道分类" prop="ctype" width="120" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gxh_channel_type" :value="scope.row.ctype" />
        </template>
      </el-table-column>

      <!-- 默认情况下若内容过多会折行显示，若需要单行显示可以使用show-overflow-tooltip属性，它接受一个Boolean，为true时多余的内容会在 hover 时以 tooltip 的形式显示出来。 -->
      <el-table-column label="简介" prop="content" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建日期" prop="createdate" width="240" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time">{{ scope.row.createdate }}</i>
          <span></span>
        </template>
      </el-table-column>

      <!-- sortable：排序 -->
      <el-table-column label="排序" prop="ordernum" width="80" align="center" sortable></el-table-column>

      <el-table-column label="是否有效" prop="isdelete" width="120" align="center">
        <template slot-scope="scope">
          <!-- 此处注意，active-value和inactive-value绑定的isdelete是数值类型，需要使用v-bind，可以缩写为:开头 -->
          <el-switch v-model="scope.row.isdelete" :active-value="0" :inactive-value="1"></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="160" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <el-pagination style="margin-top: 10px" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="queryParams.pageno" :page-size="queryParams.pagesize" :total="total" layout="->, total, sizes, prev, pager, next, jumper" :page-sizes='pageSizes'>
    </el-pagination>

    <!-- 新增与修改页面 -->
    <!-- Dialog 自身是否插入至 body 元素上。嵌套的 Dialog 必须指定该属性并赋值为 true	 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="频道名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" maxlength="50" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="频道分类" prop="ctype">
          <el-select v-model="form.ctype" placeholder="请选择分类" clearable>
            <el-option v-for="dict in dict.type.gxh_channel_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="简介" prop="content">
          <!-- <editor v-model="form.content" :min-height="200"></editor> -->
          <el-input type="textarea" v-model="form.content" rows="6" placeholder="请输入简介"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="ordernum">
          <el-input-number v-model="form.ordernum" controls-position="right" :min="1" :max="999" :precision="0"></el-input-number>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import channelApi from "@/api/gxh/channel";

export default {
  name: "Channel",
  dicts: ["gxh_channel_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 是否可以点击删除按钮
      canDelete: false,
      // 多选框选中的数据id
      ids: [],
      // 列表查询入参
      queryParams: {
        pageno: 1,
        pagesize: 10,
        name: "",
        ctype: "",
        querydate: [],
      },
      channelList: [],
      total: 0,
      // 下拉分页数，需配合layout中sizes使用
      pageSizes: [2, 10, 20, 50, 100],
      title: "频道新增",
      // 默认不显示弹出层
      dialogFormVisible: false,
      form: {
        id: "",
        name: "",
        ctype: "",
        content: "",
        ordernum: 1,
      },
      rules: {
        name: [
          {
            required: true,
            message: "频道名称不能为空",
            trigger: "blur",
          },
        ],
        ctype: [
          {
            required: true,
            message: "分类不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      channelApi.getList(this.queryParams).then((response) => {
        // 取消显示加载效果
        this.loading = false;
        this.channelList = response.data.records;
        this.total = response.data.total;
      });
    },
    handleSizeChange(size) {
      // 当前选择的size数
      console.log("size:::{}", size);
      this.queryParams.pagesize = size;
      this.getList();
    },
    handleCurrentChange(pageno) {
      // 当前选择的pageno数
      console.log("pageno:::{}", pageno);
      this.queryParams.pageno = pageno;
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageno = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDelete(id) {
      // 删除操作
      this.$confirm("是否确认删除该数据项？", "提示信息", {
        type: "warning",
        // 是否将取消（点击取消按钮）与关闭（点击关闭按钮或遮罩层、按下 ESC 键）进行区分
        distinguishCancelAndClose: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        // 显示右上角关闭按钮，默认：true
        showClose: true,
      })
        .then(() => {
          channelApi.delChannel(id).then((response) => {
            this.getList();
            this.$message({
              type: "success",
              message: "删除成功",
              // 1s后消失
              duration: 1000,
            });
          });
        })
        .catch((action) => {
          // 区分点击事件，cancel：取消，close：关闭
          console.log(action);
        });
    },
    // 批量删除
    handleDeleteBatch() {
      // 删除操作
      this.$confirm("是否确认删除该数据项？", "提示信息", {
        type: "warning",
        // 是否将取消（点击取消按钮）与关闭（点击关闭按钮或遮罩层、按下 ESC 键）进行区分
        distinguishCancelAndClose: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        // 显示右上角关闭按钮，默认：true
        showClose: true,
      })
        .then(() => {
          channelApi.delChannelBatch(this.ids).then((response) => {
            this.$message({
              type: "success",
              message: "删除成功",
              // 1s后消失
              duration: 1000,
            });
            this.getList();
            this.canDelete = false;
          });
        })
        .catch((action) => {
          // 区分点击事件，cancel：取消，close：关闭
          console.log(action);
        });
    },
    // 新增
    handleAdd() {
      console.log("add.........");
      // 清空数据
      this.reset();
      this.dialogFormVisible = true;
      this.title = "新增页面";
    },
    // 表单重置
    reset() {
      this.form = {
        id: "",
        name: "",
        ctype: "",
        content: "",
        ordernum: 1,
      };
      this.resetForm("form");
    },
    // 提交新增或修改表单
    submitForm() {
      this.$refs["form"].validate((valid) => {
        // true,false
        // console.log(valid);
        if (valid) {
          console.log("id:" + this.form.id);
          if (this.form.id) {
            channelApi.updateChannel(this.form).then((response) => {
              console.log("response:" + JSON.stringify(response));
              if (response.code == 200) {
                this.$message({
                  type: "success",
                  message: "修改成功！！！",
                  duration: 1000,
                });
                this.dialogFormVisible = false;
                this.getList();
              }
            });
          } else {
            channelApi.addChannel(this.form).then((response) => {
              console.log("response:" + JSON.stringify(response));
              if (response.code == 200) {
                this.$message({
                  type: "success",
                  message: "新增成功！！！",
                  duration: 1000,
                });
                this.dialogFormVisible = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    // 点击取消
    cancel() {
      this.reset();
      this.dialogFormVisible = false;
    },
    // 修改数据
    handleUpdate(row) {
      console.log("row:", row);
      this.reset();
      this.dialogFormVisible = true;
      this.title = "修改菜单";
      channelApi.detailChannel(row.id).then((response) => {
        console.log("response:", response);
        this.form = response.data.channel;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      if (this.ids && this.ids.length > 0) {
        this.canDelete = true;
      } else {
        this.canDelete = false;
      }
    },
    handleExport(){
      this.download('gxh/channel/export', {
        ...this.queryParams
      }, `导出文档.xlsx`)
    },
    handleExportEasyExcel(){
      this.download('gxh/channel/export/easyexcel', {
        ...this.queryParams
      }, `导出文档.xlsx`)
    }
  },
};
</script>

<style scoped>
</style>